package student

import (
	"mytest/initialize"
	"mytest/models"
	"mytest/models/request"
	"mytest/until"

	"gorm.io/gorm"
)

//增删改查

func Create(db *gorm.DB, s *models.Student) error {
	return db.Model(s).Create(s).Error
}
func Update(db *gorm.DB, s *models.Student) error {
	var count int64
	if err := db.Model(s).Where("id = ?", s.ID).Count(&count).Error; err != nil {
		return err
	}
	if count == 0 {
		return Create(db, s)
	}

	return db.Model(s).Where("id = ?", s.ID).Updates(s).Error
}

func DeleteById(db *gorm.DB, id uint) error {
	tmpdb := db.Delete(&models.Student{}, id)
	if tmpdb.RowsAffected == 0 {
		return initialize.ErrNoRowsAffected
	}
	return nil
}

func GetStuList(db *gorm.DB, req request.StudentList) (err error, list interface{}, total int64) {
	db = db.Model(&models.Student{})
	var out []models.Student
	if req.Name != "" {
		db = db.Where("name like ?", until.Fuzzy(req.Name))
	}
	var count int64
	err = db.Count(&count).Error
	if err != nil {
		return err, nil, 0
	}

	if req.Desc {
		err = db.Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Order(req.OrderKey).Find(&out).Error
		if err != nil {
			return err, nil, 0
		}
	} else {
		err = db.Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Find(&out).Error
		if err != nil {
			return err, nil, 0
		}
	}
	return nil, out, count
}
